iT邦幫忙

2025 iThome 鐵人賽

DAY 23
0
自我挑戰組

Leetcode 自學系列 第 23

自學Leetcode Day23

  • 分享至 

  • xImage
  •  

121. Best Time to Buy and Sell Stock

  1. 題目說明給定一個整數陣列 prices,第 i 個元素代表第 i 天的股票價格。
    你只能在某一天買入並在之後的某一天賣出,求你能獲得的最大利潤。
    若無法獲利,回傳 0。
    2.解題思路:
    這題的關鍵是:「找到最低點買進,再在之後的高點賣出」
    所以我們在遍歷過程中,只要:
  • 紀錄目前為止的最低價格 minPrice
  • 計算當天賣出的潛在利潤 profit = prices[i] - minPrice
  • 更新最大利潤 maxProfit = Math.max(maxProfit, profit)
    3.範例:
    輸入:prices = [7, 1, 5, 3, 6, 4]
    過程:https://ithelp.ithome.com.tw/upload/images/20251005/20169241phip2JTEoe.png
    輸出:5
    最佳策略:在價格 = 1 時買入,在價格 = 6 時賣出。
    4.另一種例子(無法獲利)
    輸入:prices = [7, 6, 4, 3, 1]
    因為價格一直下降 → 沒有賣出能賺錢的時機。
    輸出:0
    5.程式碼截圖:https://ithelp.ithome.com.tw/upload/images/20251005/2016924121mlEWFwhU.png
    6.學習心得:這題我覺得蠻有趣的,是一個會讓我想嘗試看看的題目,在解題過程中我發現只要掌握「保持最低點、計算最大差。」這句話,題目好像就比較簡單了,很開心自己又學會了一題。

上一篇
自學Leetcode Day22
系列文
Leetcode 自學23
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言